package com.zhanghe.study;

import com.zhanghe.study.model.TestAnn;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * 测试注解方式执行
 * @author zh
 * @date 2021/4/9 18:19
 */
public class MainAnn {
    private static final SessionFactory sessionFactory;
    // 创建sessionFactory对象
    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure()
            .addAnnotatedClass(TestAnn.class);

            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static void main(String[] args) {
        Session session = sessionFactory.openSession();
        try{
            TestAnn ann = (TestAnn) session.get(TestAnn.class,1);
            System.out.println(ann);
            session.close();
        } finally {
            if(session != null && session.isOpen()){
                session.close();
            }
            if(sessionFactory != null && !sessionFactory.isClosed()){
                sessionFactory.close();
            }
        }
    }
}
